import Vue from 'vue'
import store from '@store'
import Router from 'vue-router'
import { importAll } from '@utils/import-all'
import { beforeEach, afterEach } from './config'

Vue.use(Router)

const routeModules = importAll(require.context('@router/modules', false, /\.js$/))
const routes = routeModules.reduce((finallRoutes, routerModule) => {
	return finallRoutes.concat(
		routerModule.module.map((item) => {
			const camelModuleName = routerModule.camelModuleName
			// 路由格式化，添加文件名为一级路由
			return Object.assign({}, item, {
				path: camelModuleName === 'index' ? item.path : `/${camelModuleName}${item.path ? '/' : ''}${item.path}`
			})
		})
	)
}, [])

const routesArray = JSON.parse(JSON.stringify(routes))
let menu = [
	{
		title: '文件类',
		icon: 'files',
		type: 'files',
		list: []
	},
	{
		title: '图表类',
		icon: 'picture-outline',
		type: 'charts',
		list: []
	},
	{
		title: '工具类',
		icon: 's-tools',
		type: 'tools',
		list: []
	},
	{
		title: '组件类',
		icon: 'pie-chart',
		type: 'components',
		list: []
	},
	{
		title: '地图类',
		icon: 'map-location',
		type: 'maps',
		list: []
	},
	{
		title: '其他类',
		icon: 'more',
		type: 'others',
		list: []
	},
	{
		title: 'canvas',
		icon: 'picture-outline',
		type: 'canvas',
		list: []
	}
]
routesArray.map((r) => {
	const modulePath = r.path.split('/')[1]
	menu.map((m, mi) => {
		if (modulePath === m.type) {
			menu[mi].list.push({
				title: r.meta.title || '无',
				path: r.path
			})
		}
	})
})
store.commit('menu', menu)
const indexRoute = {
	path: '/',
	component: () => import('@views/index/Index.vue'),
	meta: {
		title: 'home'
	}
}
const errorRoute = {
	path: '*',
	component: () => import('@views/404/NotFound.vue'),
	meta: {
		title: '404'
	}
}
routes.push(indexRoute)
routes.push(errorRoute)

// 注入默认配置和路由表
const routerInstance = new Router({
	mode: 'history',
	routes
})
routerInstance.beforeEach(beforeEach)
routerInstance.afterEach(afterEach)
export default routerInstance
